package com.yuan.yblog.search.listener;

import com.alibaba.otter.canal.client.CanalConnector;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.crud.service.IPostService;
import com.yuan.yblog.search.config.RabbitmqConfig;
import com.yuan.yblog.search.pojo.PostMessage;
import com.yuan.yblog.search.service.EsPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author hepeiyuan on 2024/6/1 19:35
 * @description mysql-es 数据同步监听器
 */
@Component
@Slf4j
public class MysqlElasticsearchSynchronizationListener {

    @Autowired
    EntityCacheService entityCacheService;

    @Autowired
    EsPostService esPostService;


    @RabbitListener(queues = {RabbitmqConfig.QUEUE_ES_MYSQL_CHANGE_SYNC})
    public void consume(PostMessage postMessage) {
        if (postMessage == null
                || postMessage.getId() == null
                || postMessage.getOperationType() == null) {
            return;
        }
        Long id = postMessage.getId();
        // 根据消息类型，执行对应的操作
        switch (postMessage.getOperationType()) {
            case INSERT -> esPostService.insert(id);
            case DELETE -> {
                entityCacheService.deleteEntity(IPostService.POST, id);
                esPostService.delete(id);
            }
            case UPDATE -> {
                entityCacheService.deleteEntity(IPostService.POST, id);
                esPostService.update(id);
            }
        }
    }
}
